"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { registerUser } from "@/lib/api";
import { useAuth } from "@/contexts/AuthContext";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { PageBackground } from "@/components/ui/page-background";
import { Slider } from "@/components/ui/slider";
import { Label } from "@/components/ui/label";
import { useUIPreferences } from '@/contexts/UIPreferencesContext';

const formSchema = z.object({
  username: z.string().min(3, "用户名至少需要3个字符。"),
  password: z.string().min(6, "密码至少需要6个字符。"),
});

export default function RegisterPage() {
  const router = useRouter();
  const { login } = useAuth();
  const [error, setError] = useState<string | null>(null);
  const { opacities, setOpacity } = useUIPreferences();
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: { username: "", password: "" },
  });

  async function onSubmit(values: z.infer<typeof formSchema>) {
    setError(null);
    try {
      await registerUser(values);
      login(values.username); // Auto-login after successful registration
      router.push("/"); // Redirect to home page
    } catch (err: any) {
      if (err.response && err.response.data && err.response.data.message) {
        setError(err.response.data.message);
      } else {
        setError("注册失败，发生未知错误。");
      }
    }
  }

  return (
    <>
      <PageBackground src="/images/backgrounds/register.jpg" opacity={opacities.register} />

      <div className="fixed bottom-4 right-4 z-50 w-48 rounded-lg border bg-background/80 p-4 shadow-lg backdrop-blur-sm">
        <Label htmlFor="opacity-slider" className="mb-2 block text-sm font-medium">背景不透明度</Label>
        <Slider
          id="opacity-slider"
          min={0}
          max={1}
          step={0.05}
          value={[opacities.register]}
          onValueChange={(value) => setOpacity('register', value[0])}
        />
      </div>

      <div className="relative z-10 flex items-center justify-center min-h-screen">
        <div className="w-full max-w-md p-8 space-y-6 bg-card text-card-foreground rounded-lg shadow-lg">
          <div className="text-center">
            <h1 className="text-3xl font-bold">创建账户</h1>
            <p className="text-muted-foreground">立即加入我们，开始您的评测之旅！</p>
          </div>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
              {error && <p className="text-sm font-medium text-destructive text-center">{error}</p>}
              <FormField control={form.control} name="username" render={({ field }) => (
                <FormItem>
                  <FormLabel>用户名</FormLabel>
                  <FormControl><Input placeholder="username" {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )} />
              <FormField control={form.control} name="password" render={({ field }) => (
                <FormItem>
                  <FormLabel>密码</FormLabel>
                  <FormControl><Input type="password" placeholder="********" {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )} />
              <Button type="submit" className="w-full">创建账户并登录</Button>
            </form>
          </Form>
          <div className="mt-4 text-center text-sm">
            已经有账户了？{" "}
            <Link href="/login" className="underline">
              点此登录
            </Link>
          </div>
        </div>
      </div>
    </>
  );
} 